<template>
  <div>
    <Row>
      <Card>
        <p slot="title">
          <Icon type="navicon-round"></Icon>
          宝贝管理
        </p>
        <VmBtable type="edit" ref="VmBtable" :columns="dataColumns" :data="dataTable" :searchparam="searchParam"
                  :exportBtn="false" :action="excelImportUrl" :actionsuccess="'student'" :batchDelBtn="false" v-on:searchFn="searchFn"
                  v-on:page-change="pageChangeFn" v-on:addFn="addFn" :operate="operate" v-on:editFn="editFn"
                  v-on:deleteFn="deleteFn"
                  v-on:importSuccess="importSuccess"
                  v-on:smartPackFn="smartPackFn"
                  v-on:kinsfolkFn="kinsfolkFn"
                  :operationWidth="300"
                  batchDelBtn="true"
                  placeholder="宝贝名关键字" searchText="宝贝名：" cleanText="刷新" :exportPath="exportPath" v-on:restFn="restFn">
          <div slot="search" class="db_inline">
            <Select v-model="searchParam.clazzId" label-in-value @on-change="queryFn" style="width:200px">
              <Option v-for="item in clazzList" :value="item.id" :key="item.id">{{ item.gradeName }}-{{ item.name }}
              </Option>
            </Select>
          </div>
        </VmBtable>
      </Card>
    </Row>
    <Modal v-model="modal.visible" :title="modal.title" v-on:on-ok="subForm" :mask-closable="false" width="900"
           v-on:on-cancel="cancelSub">
      <Form ref="Form" :model="modal.form" :label-width="100" label-position="right" :rules="modal.rules">
        <Row>
          <Col :span="modal.isEdit?24:16">
            <Collapse value="1">
              <Panel name="1">
                小朋友信息
                <div slot="content">
                  <Row>
                    <Col span="12">
                      <FormItem label="姓名" prop="name">
                        <Input v-model="modal.form.name" placeholder="请输入幼儿名字"/>
                      </FormItem>
                      <FormItem label="性别" prop="sex">
                        <RadioGroup v-model="modal.form.sex">
                          <Radio label='女'>女</Radio>
                          <Radio label='男'>男</Radio>
                        </RadioGroup>
                      </FormItem>
                      <FormItem label="班级" prop="clazzId">
                        <Select v-model="modal.form.clazzId" label-in-value @on-change="clazzChange">
                          <Option v-for="item in clazzList" :value="item.id" :key="item.id">{{ item.gradeName }}-{{
                              item.name
                            }}
                          </Option>
                        </Select>
                      </FormItem>
                      <FormItem label="出生日期" prop="birthday">
                        <DatePicker v-model="modal.form.birthday" :options="birthdayOption" @on-change="($event)"
                                    type="date"
                                    placeholder="请选择出生日期"></DatePicker>
                      </FormItem>
                    </Col>
                    <Col span="12">
                      <FormItem label="头像" style="position: relative;" prop="avatar">
                        <LogoUpload ref="avatarUpload" accept="image/*" @get-file="getUploadFile" :multiple="false"
                                    delImgPath="student/avatar"></LogoUpload>
                      </FormItem>
                      <FormItem label="状态" prop="status" v-if="modal.isEdit">
                        <RadioGroup v-model="modal.form.status">
                          <Radio label='1'>在读</Radio>
                          <Radio label='0'>已转园</Radio>
                          <Radio label='2'>已毕业</Radio>
                        </RadioGroup>
                      </FormItem>
                      <FormItem label="转园时间" v-if="modal.form.status==='0'" prop="transferTime">
                        <DatePicker v-model="modal.form.transferTime" @on-change="($event)" type="date"
                                    placeholder="选择转园时间"></DatePicker>
                      </FormItem>
                      <FormItem label="IC卡号" prop="icCard">
                        <Input v-model="modal.form.icCard" placeholder="请输入ic卡号"/>
                      </FormItem>
                      <FormItem label="备注" prop="remark">
                        <Input v-model="modal.form.remark" type="textarea" :rows="2" :autosize="{minRows: 3,maxRows: 5}"
                               placeholder="备注信息"></Input>
                      </FormItem>
                    </Col>
                  </Row>
                </div>
              </Panel>
            </Collapse>
          </Col>
          <Col span="8" v-if="!modal.isEdit">
            <Collapse value="1">
              <Panel name="1">
                家长信息
                <div slot="content" style="height: 273px">
                  <FormItem label="监护人" prop="parentName">
                    <Input v-model="modal.form.parentName" placeholder="请输入监护人名字"/>
                  </FormItem>
                  <FormItem label="与宝贝关系" prop="parentType">
                    <Select v-model="modal.form.parentType" label-in-value>
                      <Option v-for="item in parentList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                  </FormItem>
                  <FormItem label="联系号码" prop="parentPhone">
                    <Input v-model="modal.form.parentPhone" placeholder="请输入联系号码"/>
                  </FormItem>
                  <FormItem label="IC卡号" prop="parentCard">
                    <Input v-model="modal.form.parentCard" placeholder="请输入ic卡号"/>
                  </FormItem>
                </div>
              </Panel>
            </Collapse>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelSub">取消</Button>
        <Button type="primary" @click="subForm" :loading="false">确定</Button>
      </div>
    </Modal>
    <Modal v-model="notice.visible" title="功能升级通知" ok-text="我知道了" cancel-text="关闭" :mask-closable="false" width="600">
      <div>
        <h1 style="text-align: center">导入模板升级通知</h1>
        <p style="text-indent: 24px;font-size: 14px;line-height: 30px">导入学生数据的excel表格格式已于2019-09-25日更新，请及时<a
          :href="exportPath" style="font-size: 16px">下载</a> 新的导入模板，届时此之前的导入模板将失效。非常感谢您的使用！</p>
      </div>
    </Modal>

    <Modal v-model="package.visible" title="智能书包" width="450">
      <Form ref="Form" :model="package.form" :label-width="100" label-position="right" :rules="package.rules">
        <FormItem label="GPS编号" prop="clazzId" style="width: 280px">
          <Select v-model="package.form.gpsCode" filterable placeholder="可输入编号搜索">
            <Option v-for="item in package.gpsList" :value="item.code" :key="item.code">
            </Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="package.visible=false">取消</Button>
        <Button type="primary" @click="subGPSForm" :loading="false">保存</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import API from "@/api/api";
import VmBtable from "@/components/vm/vm-btable";
import LogoUpload from "@/components/views/upload/Upload"
import Axios from 'axios'
import Cookie from "js-cookie"

export default {
  components: {
    VmBtable,
    LogoUpload
  },
  data() {
    const phoneValidate = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入联系人电话'));
      } else {
        callback();
      }
    };
    return {
      package: {
        gpsList: [],
        visible: false,
        form: {
          gpsCode: '',
          studentId: ''
        },
        rules: {}
      },
      birthdayOption: {
        disabledDate(date) {
          let now = new Date();
          return date > now - 43200000000;
        }
      },
      searchParam: {
        current: 1,
        size: 20,
        total: 0,
        name: '',
        clazzId: '',
      },
      exportPath: 'http://www.wekids.group/student.xlsx',
      excelImportUrl: Axios.defaults.baseURL + '/student/import',
      dataColumns: [
        {
          type: 'selection',
          align: 'center',
          minWidth: 30
        },
        {
          title: '序号',
          type: 'index',
          align: 'center',
          minWidth: 100,
        },
        {
          title: '名称',
          align: 'center',
          key: 'name',
          minWidth: 100,
        },
        {
          title: '性别',
          align: 'center',
          key: 'sex',
          minWidth: 100,
        },
        {
          title: '编号',
          align: 'center',
          key: 'code',
          minWidth: 100,
        },
        {
          title: '班级',
          align: 'center',
          key: 'clazzName',
          minWidth: 160,
        },
        {
          title: 'IC卡号',
          align: 'center',
          key: 'icCard',
          minWidth: 100,
        },
        {
          title: '人脸信息',
          align: 'center',
          key: 'face',
          minWidth: 100,
          render: (h, param) => {
            let face = param.row.face;
            let desc = '未录入';
            if (face.startsWith('2')) {
              desc = '生成失败';
            } else if (face.startsWith('0')) {
              desc = '生成中';
            } else if (face.startsWith('1')) {
              desc = '已录入'
            }
            return h('div', {}, desc);
          }
        },
        {
          title: '状态',
          align: 'center',
          key: 'status',
          minWidth: 100,
          sortable: true,
          sortType: 'desc',
          render: (h, param) => {
            let str = '在读';
            let color = 'green';
            if (param.row.status === 0) {
              str = '已转园';
              color = 'orange'
            } else if (param.row.status === 2) {
              str = '已毕业';
              color = 'blue'
            }
            return h('div', {
              style: {
                color: color
              }
            }, str);
          }
        },
        {
          title: '家长信息（人）',
          align: 'center',
          key: 'kinsfolkList',
          minWidth: 100,
          render: (h, param) => {
            return h('div', {}, param.row.kinsfolkList.length);
          }
        },
      ],
      operate: [],
      dataTable: [],
      clazzList: [],
      parentList: [
        {
          id: '爸爸', 'name': '爸爸'
        },
        {
          id: '妈妈', 'name': '妈妈'
        },
        {
          id: '其他', 'name': '其他'
        },
      ],
      modal: {
        visible: false,
        title: '',
        isEdit: false,
        loading: false,
        form: {
          name: '',
          sex: '女',
          status: '1',
          icCard: '',
          birthday: '',
          entryTime: '',
          transferTime: '',
          graduateTime: '',
          initHeight: '',
          initWeight: '',
          clazzId: '',
          clazzName: '',
          remark: '',
          parentName: '',
          parentPhone: '',
          parentType: '',
          parentCard: '',
        },
        rules: {
          'name': [{
            required: true,
            trigger: 'blur',
            message: '必填项'
          }],
          'clazzId': [{
            type: 'number',
            required: true,
            trigger: 'blur',
            message: '必填项'
          }],
          'birthday': [{
            required: true,
            type: 'date',
            trigger: 'blur',
            message: '必填项'
          }],
          'clazzName': [{
            required: true,
            trigger: 'blur',
            message: '必填项'
          }],
          'parentName': [{
            trigger: 'blur',
          }],
          'parentPhone': [{
            trigger: 'blur',
            validator: phoneValidate,
          }],
          'parentType': [{
            message: '必填项'
          }],
        }
      },
      parent: {
        title: '',
        visible: false,
        list: []
      },
      notice: {
        visible: false,
      }
    };
  },
  methods: {
    smartPackFn(data) {
      this.package.visible = true;
      this.package.form.studentId = data.id;
      this.package.form.gpsCode = data.gpsCode;
      API.fetchGpsList().then(resp => {
        this.package.gpsList = resp.data;
      })
    },
    subGPSForm() {
      API.bindGPS(this.package.form).then(resp => {
        this.package.visible = false;
        this.queryFn();
      })
    },
    importSuccess() {
      this.queryFn();
      this.fetchKindergartenClazz();
    },
    getUploadFile(oldList, newFile) {
      this.modal.form.avatar = newFile.name;
    },
    addFn() {
      Object.assign(this.modal, {
        visible: true,
        isEdit: false,
        title: '添加',
      })
    },
    editFn(data) {
      Object.assign(this.modal, {
        visible: true,
        isEdit: true,
        title: '编辑',
      })
      Object.assign(this.modal.form, data);
      this.modal.form.sex = data.sex
      this.modal.form.status = data.status + ''
      let avatar = data.avatar;
      if (!avatar) {
        return;
      }
      this.$refs.avatarUpload.acceptImageList([{
        id: avatar,
        key: avatar,
        fname: avatar,
        type: 'pic'
      }])
    },
    deleteFn(data) {
      for (let i = 0; i < data.length; i++) {
        API.deleteStudent({
          id: data[i].id
        }).then(resp => {
          this.queryFn();
        })
      }
    },
    restFn() {
      this.searchParam.current = 1;
      this.searchParam.size = 20;
      this.searchParam.name = '';
      this.searchParam.clazzId = '';

      this.queryFn();
    },
    queryFn() {
      API.fetchStudent(this.searchParam).then(
        res => {
          let data = res.data;
          this.dataTable = data.records;
          this.searchParam.total = data.total;
        },
        error => {
          this.$Message.info(error.msg);
        }
      );
    },
    complete() {
      Object.assign(this.modal, {
        visible: false,
        title: '',
        loading: false,
      });
      this.$refs.Form.resetFields();
      this.$refs.avatarUpload.acceptImageList([]);
    },
    subForm() {
      this.$refs.Form.validate(valid => {
        if (valid) {

          let data = Object.assign(this.modal.form);
          this.modal.loading = true;
          if (data.id) {
            API.updateStudent(data).then(resp => {
              this.complete();
              this.queryFn();
            }).catch(resp => {
              this.modal.loading = false;
            })
          } else {
            API.createStudent(data).then(resp => {
              this.complete();
              this.queryFn();
            }).catch(resp => {
              this.modal.loading = false;
            })
          }
        }
      })
    },
    cancelSub() {
      this.complete();
    },
    pageChangeFn(current) {
      this.searchParam.current = current;
      this.queryFn();
    },
    searchFn(value) {
      this.searchParam.name = value;
      this.queryFn();
    },
    fetchKindergartenClazz() {
      API.fetchKindergartenClazz().then(resp => {
        this.clazzList = resp.data;
      })
    },
    clazzChange(data) {
      if (data) {
        this.modal.form.clazzId = data.value;
        this.modal.form.clazzName = data.label;
      }
    },
    kinsfolkFn(obj) {
      this.$router.push({
        path: '/kinsfolk',
        query: obj
      })
    },
  },
  created() {
    let know = Cookie.get("know");
    if (!know) {
      //this.notice.visible = true;
      Cookie.set("know", 1);
    }
  },
  mounted() {
    this.queryFn();
    this.fetchKindergartenClazz();
    this.operate = [{
      name: '家长信息',
      type: 'info',
      size: 'small',
      method: 'kinsfolkFn'
    },
      {
        name: '编辑',
        type: 'info',
        size: 'small',
        method: 'editFn'
      },
      /*  {
          name: '智能书包',
          type: 'info',
          size: 'small',
          method: 'smartPackFn'
        },*/
      {
        name: '删除',
        type: 'error',
        size: 'small',
        method: 'deleteFn'
      }]
  }
}
</script>

<style scoped>

</style>
